import React, { Component } from 'react';
import { ListView, Carousel, WingBlank} from 'antd-mobile';
import './PingTuan.css';
import emptyImage from '../image/emptyImgae.png';
import groupShop from '../image/groupShop.png';

export default class PingTuan extends Component {

    constructor(props){
        super(props);
        var ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => { return r1 !== r2; } });
        this.state = {
            dataSource: ds.cloneWithRows([]),
            data : [],
            imgHeight: '46.6vw',
            listViewH: 'calc(100vh - 46.6vw)',
            tips : '客官，暂无拼团商品哦~',
            noMoreData : false,

            isOkToShopingBGColor :'#d72c2a',
            isWaitToShopingBGColor :'#fff',
            isUnAbleShopingBGColor :'#ccc',

            pageIndex: 1
        }
        this.dsDataLists = [];
        this.renderItem = this.renderItem.bind(this)
    }

    componentDidMount(){
        setTimeout(() => {
            this.setState({
                data: ['AiyWuByWklrrUDlFignR',],
            });
        }, 100);

 
        // 加载拼团商品列表
        this.handleUserPullGroupShopGoodsLists()
    }
    // 加载拼团商品列表
    handleUserPullGroupShopGoodsLists(isRefresh){
        var self = this;
        // 拿Token
        var access_token = '';
        if (window.ewgNativeObject) {
            access_token = window.ewgNativeObject.ewg_getToken();
        }
        
        var header = {
            "Content-Type": "application/json;charset=UTF-8",
            "Authorization": '',  //用户登陆后返回的token，某些涉及用户数据的接口需要在header中加上token
        };
        var params = {
            device :'HTML5',
            page: this.state.pageIndex,
            pageSize : '20'
        }

        fetch('http://localhost:3000/api/Goods/team_goods.html',{
            method:'POST',
            headers:header,
            body: JSON.stringify(params)
        }).then((response) => response.json()).then(res=>{
            if (res.code === 0) {
                if (res.data.length <= 20) {
                    //console.log('全部加载完毕');
                    self.setState({ noMoreData: true })
                }
                res.data.map((item,index)=>{
                    item.key = index
                })
                self.dsDataLists = self.dsDataLists.concat(res.data);
                self.setState({
                    dataSource: self.state.dataSource.cloneWithRows(self.dsDataLists),
                    pageIndex: self.state.pageIndex + 1,
                }) 
            }
        }).catch(err=>{

        });
    }

    //  用户点击轮播图
    userClickBannerAction(props){
        console.log('点击banner图')
    }
    // 用户点击拼团或者点击待开始拼团
    handleUserClickJoinShopGroupAction(item){
        console.log('handleUserClickJoinShopGroupAction' + item);
        if (window.ewgNativeObject) {
            let action = "_ewg_product_ewg_"+item.goods_id+'_ewg_'
            window.ewgNativeObject.ewg_runAction(action);
        }
    }

    renderItem(item, section, index){
        //console.log(item)
        return (<div style={{height:'130px',backgroundColor:'white',alignItems:'center',display:'flex',flexDirection:'row'}} key={index}>
            <div style={{marginLeft:'15px',width:'100px',height:'100px',backgroundColor:'pink'}}>
                <img style={{width:'100%',height:'100%'}} alt='' src={item.goods_img}></img>
            </div>

            <div style={{display:'flex',flex:1,marginLeft:'10px',marginRight:'15px',backgroundColor:'white',height:'100px',flexDirection:'column'}}>
                <label className='num2' style={{ fontSize: 14, color: '#333', fontWeight: 500, backgroundColor: 'white','-webkit-line-clamp':'2','-webkit-box-orient':'vertical'}}>{item.goods_name}</label>

                <div style={{marginTop:'14px',height:'14px',backgroundColor:'white',flexDirection:'row',alignItems:'center',display:'flex'}}>
                    <img style={{ height: '12px', width: '12px', alignSelf: 'center' }} alt='' src={groupShop}></img>
                    <label style={{ fontSize: '12px', fontWeight: 500, alignSelf: 'center',height:'12px',lineHeight:'12px',color:'#333'}}>{item.people}人团</label>
                    <label style={{ fontSize: '12px', fontWeight: 500, alignSelf: 'center', marginLeft: '10px', color: '#999', height: '12px', lineHeight: '12px'}}>已拼{item.stock}件</label>
                </div>

                <div style={{marginTop:'11px',height:'25px',backgroundColor:'white',display:'flex',alignItems:'center',flexDirection:'row'}}>
                    <label style={{fontSize:'18px',color:'#d72c2a',fontWeight:'500'}}>￥</label>
                    
                        
                        <label style={{ fontSize: '22px', color: '#d72c2a', fontWeight: 500 }}>{item.activity_price}
                    
                        </label>
                    <div style={{ textDecoration: 'line-through', color:'#999',fontWeight:1000,marginLeft:'10px'}}>
                        <label style={{ fontSize: '13px', color: '#999', fontWeight: 1000, }}>￥{item.goods_price}</label>
                    </div>
                    
                    <div style={{ flex: 1, display: 'flex', backgroundColor: 'white', height: '100%', justifyContent: 'flex-end' }} onClick={this.handleUserClickJoinShopGroupAction.bind(this,item)}>
                        <label style={{ borderRadius: 3, borderWidth: 0, backgroundColor: 'pink', fontSize: '14px', height: '25px', lineHeight: '25px', fontWeight: 500, color: 'white' }}><WingBlank>立即拼</WingBlank></label>
                    </div>  
                </div>
            </div>


        </div>);
    }

    loadMore(){
        console.log('加载更多');
        var self = this;
        this.setState({pageIndex : this.state.pageIndex+1},()=>{
            self.handleUserPullGroupShopGoodsLists()
        })
    }

    render() {
        return (
            <div style={{height:'100%',width:'100%',margin:0,}}>
                <div>
                    <Carousel
                        dots={false}
                        autoplay={true}
                        infinite
                        beforeChange={(from, to) => console.log(`slide from ${from} to ${to}`)}
                        afterChange={index => console.log('slide to', index)}
                    >
                        {this.state.data.map((val,index) => (
                            <div key={index}
                                style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
                            >
                                <img
                                    onClick={this.userClickBannerAction.bind(this)}
                                    src={`https://zos.alipayobjects.com/rmsportal/${val}.png`}
                                    alt=""
                                    style={{ width: '100%', verticalAlign: 'top' }}
                                    onLoad={() => {
                                        // fire window resize event to change height
                                        window.dispatchEvent(new Event('resize'));
                                        this.setState({ imgHeight: 'auto' });
                                    }}
                                />
                            </div>
                        ))}
                    </Carousel>
                </div>

                <div>
                    {this.state.dataSource.rowIdentities[0].length > 0 ?
                    <div >
                     <ListView
                        contentContainerStyle={{ border: 0 }}
                        style={{ height:this.state.listViewH }}
                        // useBodyScroll
                        ref={el => this.lv = el}
                        dataSource={this.state.dataSource}
                        renderRow={this.renderItem}
                        onScroll={() => { console.log('onscroll') }}
                        scrollEventThrottle={200}
                        onEndReached={() => this.loadMore()}
                        className="am-list sticky-list"
                        onEndReachedThreshold={0.01}
                        renderSeparator={(index, section) => { return section === this.state.dataSource.rowIdentities[0].length - 1 ? null : <div key={section} style={{height:'10px',backgroundColor:'#fafafa'}}></div>}}
                        renderFooter={() => { return <div style={{display: 'flex',justifyContent:'center',alignItems:'center',backgroundColor:'#fafafa',height:30,}}><label>{this.state.noMoreData ? '没有更多数据...' : '正在加载...'}</label></div> }}
                    ></ListView> 
                    </div>
                    :
                        <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column', marginTop: '12vh' }}>
                            <img alt='' src={emptyImage}
                                style={{ width: '40%', alignSelf: 'center' }} />
                            <label style={{ marginTop: '15px', fontSize: '15px', color: '#666' }}>{this.state.tips}</label>
                        </div>
                    }
                </div>

            </div>

        );
    }
}